package com.malljelly.study.controller;

import com.malljelly.study.service.CallbackService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sdk.AcpService;
import sdk.LogUtil;
import sdk.SDKConstants;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by 骑着蜗牛去旅行 on 2018/8/16.
 */
@Api("银联支付回调")
@RestController  //@Controller+@ResponseBody
@RequestMapping("soa/unionPayService/callback")
@Slf4j
public class YinLianCallbackController extends BaseController {

    @Autowired
    private CallbackService callbackService;
    private static final String PAY_SUCCESS = "pay_success";
    private static final String PAY_FAIL = "pay_fail";


    /**
     * 功能说明:同步回调
     *
     * @return
     */
    @RequestMapping("/syn")
    public String syn(HttpServletRequest request) {
        Map<String, String> synResultMap = callbackService.syn(request);
        String encoding = request.getParameter(SDKConstants.param_encoding);
        if (!AcpService.validate(synResultMap, encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");
            return PAY_FAIL;
        }
        request.setAttribute("txnAmt", Double.parseDouble(synResultMap.get("txnAmt")) / 100);
        request.setAttribute("orderId", Long.parseLong(synResultMap.get("orderId")));
        LogUtil.writeLog("验证签名结果[成功].");

        LogUtil.writeLog("订单号为:"+Long.parseLong(synResultMap.get("orderId"))+"====金额"+Double.parseDouble(synResultMap.get("txnAmt")) / 100);

        return PAY_SUCCESS;
    }

    /**
     * 功能说明:异步回调
     *
     * @return
     */
    @RequestMapping("/asyn")
    public String asyn(HttpServletRequest request) {
        return callbackService.asyn(request);
    }

}
